import {
  createRouter,
  createWebHashHistory,
  NavigationGuardNext,
  RouteLocationNormalized,
  RouteRecordRaw,
} from "vue-router";
import "nprogress/nprogress.css";
import { usePermissionStore } from "@/store";
import { clearToken, getAccessToken, getRefreshToken } from "@/utils/cacheUtils";
import { MenuTypeEnum } from "@/enums/MenuTypeEnum";
import router from "@/router";
import NProgress from "@/utils/nprogress";

export function setupPermission() {
  let whiteList = ["/login"];

  // 需要在beforeEach里面使用pinia，否则无法成功初始化
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const token = !!getAccessToken();
    const refresh = !!getRefreshToken();
    if (token && refresh) {
      if (to.path == "/login") {
        next();
        NProgress.done();
      } else {
        const permissionStore = usePermissionStore();
        if (permissionStore.isRoutesLoaded) {
          // 未匹配到任何路由，跳转404
          if (to.matched.length === 0) {
            next("/404");
          } else {
            // 动态设置页面标题
            const title = (to.params.title as string) || (to.query.title as string);
            if (title) {
              to.meta.title = title;
            }
            await permissionStore.loadButton(to.meta?.id as string);
            next();
          }
        } else {
          try {
            // 生成动态路由
            const dynamicRoutes = await permissionStore.generateRoutes();
            dynamicRoutes.forEach((route: RouteRecordRaw) => {
              if (!route?.meta?.parentId && route?.meta?.menuType === MenuTypeEnum.Menu) {
                router.addRoute("/", route);
              } else {
                router.addRoute(route);
              }
            });
            if (dynamicRoutes.length === 1) {
              next({ ...dynamicRoutes[0], replace: true });
            } else {
              next({ ...to, replace: true });
            }
          } catch (error) {
            // 移除 token 并跳转登录页
            clearToken();
            // next(`/login?redirect=${to.path}`);
            redirectToLogin(to, next);
            NProgress.done();
          }
        }
      }
    } else {
      // 未登录可以访问白名单页面
      if (whiteList.indexOf(to.path) != -1) {
        next();
      } else {
        // next(`/login?redirect=${to.path}`);
        redirectToLogin(to, next);
        NProgress.done();
      }
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });
}
// 重定向到登录页
function redirectToLogin(to: RouteLocationNormalized, next: NavigationGuardNext) {
  const params = new URLSearchParams(to.query as Record<string, string>);
  const queryString = params.toString();
  const redirect = queryString ? `${to.path}?${queryString}` : to.path;
  next(`/login?redirect=${encodeURIComponent(redirect)}`);
}
